using System;
using IFXplus.SmartStorage.Settings;

namespace IFXplus.SmartStorage.Providers
{
    internal class WebServiceStorageProvider : IStorageProvider
    {

        #region Privates

        private readonly StorageProviderReference _reference = null;
        private readonly WebServiceStorageProviderSettings _settings = null;

        private readonly WebServiceStorageProviderStub _service = null;

        #endregion

        #region Constructor

        public WebServiceStorageProvider(StorageProviderReference reference)
        {
            if (reference == null)
                throw new ArgumentNullException("reference");
            if (string.IsNullOrEmpty(reference.Id))
                throw new ArgumentException("reference.Id cannot be null or empty", "reference");
            _reference = reference;
            _settings = StorageSettings.GetInstance().GetStorageProviderSettings<WebServiceStorageProviderSettings>(reference.Id);
            if (_settings == null)
                throw new StorageSettingsException(string.Format("{0} provider settings not found", reference));

            _service = new WebServiceStorageProviderStub(Settings.Url, Settings.Username, Settings.Password);
        }

        #endregion

        #region Properties

        private WebServiceStorageProviderSettings Settings
        {
            get { return _settings; }
        }

        #endregion

        #region IStorageProvider Members

        public StorageProviderReference Reference
        {
            get { return _reference; }
        }

        public void Insert(StorageEntry value)
        {
            if (Settings.AllowWrite)
                _service.Insert(value);
        }

        public void Remove(string key)
        {
            if (Settings.AllowWrite)
                _service.Remove(key);
        }

        public StorageEntry Get(string key)
        {
            return (Settings.AllowRead) ? _service.Get(key) : null;
        }

        #endregion
    }
}
